<?php
class DownloadForm extends Form
{
    const FIELD_FIRST_NAME = 'first_name';
    const FIELD_LAST_NAME  = 'last_name';
    const FIELD_EMAIL      = 'email';
    const FIELD_PHONE      = 'phone';

    protected static $errorMap = array(
        'first_name_required' => array('message' => 'Please enter your first name', 'level' => self::ERROR_LEVEL_ERROR, 'field_name' => 'First Name'),
    	'last_name_required'  => array('message' => 'Please enter your last name', 'level' => self::ERROR_LEVEL_ERROR, 'field_name' => 'Last Name'),
        'email_required'      => array('message' => 'Please enter a valid e-mail address', 'level' => self::ERROR_LEVEL_ERROR, 'field_name' => 'Email'),
        'email_invalid'       => array('message' => 'Please enter existing e-mail address', 'level' => self::ERROR_LEVEL_ERROR, 'field_name' => 'Email')
      );

    protected function GetTemplatePath()
    {
        return 'include/forms/download_form.tpl';
    }

    public function Setup()
    {
        $this->SetFields( array(
            self::FIELD_FIRST_NAME, self::FIELD_LAST_NAME, self::FIELD_EMAIL, self::FIELD_PHONE
        ));
    }

    protected function Validate()
    {
        parent::Validate();

        $firstName = preg_replace('/\s+/', ' ', $this->GetParamValue(self::FIELD_FIRST_NAME, ''));
        if (!empty($firstName))
        {
            $this->SetValue(self::FIELD_FIRST_NAME, $firstName);
        }
        else
        {
            $this->SetError(self::FIELD_FIRST_NAME, self::$errorMap['first_name_required']);
        }

        $lastName = preg_replace('/\s+/', ' ', $this->GetParamValue(self::FIELD_LAST_NAME, ''));
        if (!empty($lastName))
        {
            $this->SetValue(self::FIELD_LAST_NAME, $lastName);
        }
        else
        {
            $this->SetError(self::FIELD_LAST_NAME, self::$errorMap['last_name_required']);
        }

        $email = filter_var($this->GetParamValue(self::FIELD_EMAIL), FILTER_VALIDATE_EMAIL);
        if ($email !== false)
        {
            if (Util::checkMXRecord($email))
            {
                $this->SetValue(self::FIELD_EMAIL, $email);
            }
            else
            {
                $this->SetError(self::FIELD_EMAIL, self::$errorMap['email_invalid']);
            }
        }
        else
        {
            $this->SetError(self::FIELD_EMAIL, self::$errorMap['email_required']);
        }

        $phone = preg_replace('/\s+/', ' ', $this->GetParamValue(self::FIELD_PHONE, ''));
        $this->SetValue(self::FIELD_PHONE, $phone);
    }
}
?>